/**
 * Created by Administrator on 2018/5/17.
 * 角色管理
 */
define(function (require,exports,module) {
    var sTpl = require("./fboRoleMgr.html");
    require("./fboRoleMgr.css");

    var VueComponent = Vue.extend({
            template: sTpl
            , methods: {
                getContextPath: function(){
                    var contextPath = document.location.pathname;
                    var contextPath = contextPath.split('/')[1];
                    var contextPath = "/" + contextPath;
                    this.contextPath = contextPath;
                },
                onSearchFwRole: function (val) {
                    var searchVal = this.formInput.key || "";
                    if (searchVal) {
                        this.urls.url = this.contextPath + this.urls.initurl + "?type=0&key=" + searchVal;
                    } else {
                        this.urls.url = this.contextPath + this.urls.initurl + "?type=0";
                    }
                },
                addFwRole: function () {
                    $('.el-input__inner').val('');
                    this.disableSaveBtn = false;
                    this.formData = {roleCode: '', roleName: '', teamId: '', roleStatus: '1', roleType: '0'};
                    //0~公共,1~私有
                    if (this.internalData.length != 0) {
                        this.formData.parentCode = this.internalData[0].roleId;
                        this.formData.parentName = this.internalData[0].roleName;
                    }
                    this.roleFormTitle = "新增角色";
                    this.$refs.table.dialogFormVisible = true;
                },
                initRolesData: function () {
                    var self = this;
                    axios.get(this.contextPath + "/api/webframe/fwrole?type=0&key=").then(function (result) {
                        var d = result.data.content;
                        if (d.length < 1) {
                            self.$message({type: "info", message: "未获取到角色信息！"});
                        } else {
                            for (var i = 0; i < d.length; i++) {
                                if (d[i].teamId) {
                                    d[i].teamName = d[i].teamPo.teamName;
                                } else {
                                    d[i].teamName = "";
                                }
                            }
                            self.rolesData = d;
                        }
                    }.bind(this));
                },
                treeNodeQuery: function (item) {

                },
                roleRowClick: function (row, event, column) {
                    this.currentRoleId = row.roleId;
                    this.currentRoleName = row.roleName;
                    this.getRoleModuleTree(row.roleId);
                    this.internalData[0] = row;
                },
                handleEdit: function (index, val) {
                    if (this.currentRoleId) {
                        this.disableSaveBtn = false;
                        this.formData = $.extend(true, {}, this.internalData[0]);
                        //0~公共,1~私有
                        this.formData.roleType = '0';//this.$data.urlParams.type=='public'?'0':'1';
                        this.formData.teamId = this.formData.teamId ? this.formData.teamId : "ALL";
                        this.roleFormTitle = "修改角色";
                        this.$refs.table.dialogFormVisible = true;
                    }
                },

                getRoleModuleTree: function (roleId) {//获取当前角色拥有的菜单
                    var self = this;
                    axios.get(this.contextPath + '/api/webframe/fwmodule/tree/role/' + roleId).then(function (data) {
                        self.roleModuleData = data.data.allData;
                        self.eachModuleData = data.data.allData;
                        var selectedIds = self.$kun.removeTreeSelectedPids(self.roleModuleData, data.data.selectId, "id", "code", "pcode", "children") || [];
                        self.$refs.roleModuleTree.setCheckedKeys(selectedIds, true);
                    });
                },
                formCancle: function () {
                    this.$refs.table.dialogFormVisible = false;
                },
                formConfirm: function () {
                    var self = this;
                    self.disableSaveBtn = true;
                    this.$refs.editForm.validate(function (valid) {
                        if (!valid) {
                            self.disableSaveBtn = false;
                            return;
                        }
                        if (self.formData.teamId == 'ALL') {
                            self.formData.roleType = '0';
                            self.formData.teamId = null;
                        } else {
                            self.formData.roleType = '1';
                        }
                        self.formData.roleStatus = self.formData.roleStatus == "1" ? "1" : "0";
                        axios.post(basepath + self.urls.initurl, self.formData).then(function (result) {
                            self.$message({type: "success", message: "角色保存成功！"});
                            //self.initRolesData();
                            if (self.formData.teamId == null) {
                                self.formData.teamId = 'ALL';
                            }
                            self.$refs.table.dialogFormVisible = false;
                            self.disableSaveBtn = false;
                            self.internalData[0] = self.formData;
                            self.$refs.table.freshTableList();
                        }).catch(function (e) {
                            self.$message.error("保存失败");
                            self.disableSaveBtn = false;
                        });

                    });
                },
                saveRoleModule: function () {
                    var moduleids = this.$refs.roleModuleTree.getCheckedKeys();
                    moduleids = this.$kun.getTreeSelectedIds(this.$refs.roleModuleTree.data, moduleids, "id", "code", "pcode", "children") || [];
                    if (this.currentRoleId == "") {
                        this.$message({type: "info", message: "请选择角色！"});
                        return;
                    }
                    var self = this;
                    var data = {
                        "moduleIds": moduleids,
                        "roleId": this.currentRoleId
                    }

                    axios.post(basepath + '/api/webframe/fwmodule/updateFwRoleModuleByRoleId', data).then(function (result) {
                        self.$message({type: "success", message: "角色授权成功！"});
                        console.log('confirmRoles ok')
                    }.bind(this));
                },
                filterTree: function (value, data, node) {
                    if (!value) {
                        return true;
                    }
                    if (data.label.indexOf(value) >= 0) {
                        return true;
                    }
                    return false;
                },
                filterMenu: function (val) {
                    var self = this;
                    self.filterMenuKey = val;
                    if (self.filterMenuKeyChange == false) {
                        self.filterMenuKeyChange = true;
                        var timeOut = window.setInterval(function () {
                            if (new Date().getTime() - self.filterMenuKeyDate > 300) {
                                self.$refs.roleModuleTree.filter(self.filterMenuKey);
                                window.clearInterval(timeOut);
                                self.filterMenuKeyChange = false;
                            }
                        }, 200);
                    }
                }

            },
            data: function () {
                var self = this;
                var validateRole = function (rule, value, callback) {
                    //if(this.$refs.editForm) this.$refs.editForm.clearValidate();

                    if (value) {
                        var paramObj = {};
                        paramObj["roleName"] = self.formData.roleName;
                        paramObj["roleCode"] = self.formData.roleCode;
                        paramObj["teamId"] = self.formData.teamId;
                        paramObj[rule.field] = value;
                        if (paramObj.teamId == 'ALL') paramObj.teamId = null;
                        axios.post(basepath + "/api/webframe/fwrole/check", paramObj
                        ).then(function (res) {
                            if (res.data.length > 0) {
                                if (self.formData.roleId) {
                                    if (res.data[0].roleId != self.formData.roleId) callback(new Error('已存在'));
                                    else callback();
                                } else callback(new Error('已存在'));
                            } else callback();
                        });
                    } else callback();
                };
                return {
                    roleFormTitle: "",
                    disableSaveBtn: false,
                    filterMenuKey: "",
                    filterMenuKeyDate: null,
                    filterMenuKeyChange: false,
                    contextPath: "",
                    formData: {},
                    formInput: {user: ""},
                    formLabelWidth: '120px',
                    internalData: [],
                    activeNames: ['1', '2', '3'],
                    rolesData: [],
                    urlParams: {},
                    myUsers: [],
                    dataUsers: [],
                    myModules: [],
                    dataModules: [],
                    roleModuleData: [],
                    eachModuleData: [],
                    teamsData: [],
                    dialogVisible: false,
                    currentRoleId: '',
                    currentRoleName: '',
                    currTeam: {},
                    roleModulePopVisible: true,
                    urls: {
                        url: basepath + "/api/webframe/fwrole",
                        initurl: "/api/webframe/fwrole",
                    },
                    rules: {
                        roleCode: [
                            {required: true, message: '请输入角色编码', trigger: 'blur'},
                            {required: true, validator: validateRole, trigger: 'blur'}
                        ],
                        roleName: [
                            {required: true, message: '请输入角色名称', trigger: 'blur'},
                            {required: true, validator: validateRole, trigger: 'blur'}
                        ],
                        teamId: [
                            {required: true, message: '请选择归属团队', trigger: 'blur'},
                            {required: true, validator: validateRole, trigger: 'change,blur'}
                        ]
                    }
                }
            },
        created: function () {
                this.getContextPath();
                var paramsArray = location.search.substring(1).split("&") || [];
                var params = {};
                $.each(paramsArray, function (index, item) {
                    if (item != "") {
                        var tmp = item.split('=')
                        params[tmp[0]] = tmp[1];
                    }
                });
                this.$data.urlParams = params;
                var type = '0';//this.$data.urlParams.type=='public'?'0':'1';
                this.urls.url = basepath + "/api/webframe/fwrole?type=" + type + "&key=";
                window.self = this;
                //this.initRolesData();
                //this.initTeamData();
                // this.urls.url = basepath+"api/appointment/findAppointment";
            },
        activated:function () {
            messages.$emit('change', '角色管理');
        },
            mounted: function () {
                setTimeout(function () {
                    $('.el-table__row:first').click();
                }, 600);
            },
            watch: {
                filterMenuKey: function (val) {
                    this.filterMenuKeyDate = new Date();
                    this.filterMenu(val);
                }
            }
        });
    module.exports = VueComponent;
})
